package net.tv90.bfmccoreqqbot.api.handler;

import com.alibaba.fastjson.JSONObject;
import net.tv90.bfmccoreqqbot.api.MessageHandler;
import net.tv90.bfmccoreqqbot.api.annotation.MessageCheck;
import net.tv90.bfmccoreqqbot.api.annotation.MessageCheckPolicy;
import net.tv90.bfmccoreqqbot.api.annotation.MessageType;
import net.tv90.bfmccoreqqbot.api.entity.MessageContext;
import net.tv90.bfmccoreqqbot.util.HttpUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@MessageType("sjh")
@MessageCheck(MessageCheckPolicy.STARTS_WITH)
public class QueryTelephoneMessageHandler implements MessageHandler {

    public static boolean isValidPhoneNumber(String phoneNumber) {
        String regex = "^1[3456789]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    @Override
    public String handleMessage(MessageContext msg) {

        String[] args = msg.getMessage().split("=");

        if (args.length == 2) {
            String phone = args[1];
            if (isValidPhoneNumber(phone)) {
                try {
                    JSONObject data = HttpUtil.httpPost("https://tenapi.cn/v2/phone", "tel=" + phone).getJSONObject("data");
                    if (data != null) {
                        String result = "手机号码:" + phone + "\n";
                        String local = data.getString("local");
                        String type = data.getString("type");
                        String isp = data.getString("isp");
                        String std = data.getString("std");
                        result += "归属地:" + local + "\n" + "卡类型:" + type + "\n" + "运营商:" + isp + "\n" + "通信标准:" + std + "\n";
                        return result;
                    } else {
                        return "手机号" + phone + "查询失败";
                    }
                } catch (Exception e) {
                    return "手机号" + phone + "查询失败";
                }
            } else {
                return "查询失败，" + phone + "不是有效的手机号";
            }
        }
        return "格式有误，格式: sjh=手机号";
    }

    @Override
    public boolean onPreHandleMessage(MessageContext msg) {
        System.out.println("接受到消息: " + msg.getMessage());
        return true;
    }
}
